<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary">
                        添加角色
                    </el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList" border stripe>
                <el-table-column type="expand">
                    <template v-slot="scope">
                        <el-row :class="['bdbottom', i1 === 0 ?'bdtop' : '', 'vcenter']" v-for="(item, i1) in scope.row.children" :key="item.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限-->
                            <el-col :span="19">
                                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2,i2) in item.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" v-for="(item3) in item2.children" :key="item3.id">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template v-slot="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini"  @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 修改用户的对话框 -->
        <el-dialog
                title="修改用户" :visible.sync="editDialogVisible"
                width="50%" @close="editDialogClosed">
                <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
                    <el-form-item label="角色名称">
                        <el-input v-model="editForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述">
                        <el-input v-model="editForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUserInfo">确 定</el-button>
                </span>
        </el-dialog>

        <!-- 分配权限对话框 -->
        <el-dialog
            title="分配权限" :visible.sync="setRightDialogVisible"
            width="50%" @close="setRightDialogClosed">
            <el-tree :default-checked-keys="defKeys" ref="treeRef" show-checkbox :data="rightsList" default-expand-all :props="treeProps" node-key="id"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button @click="allotRights"  type="primary">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {

        var checkEmail = (rule, value, cb) => {
            //验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regEmail.test(value)){
                return cb()
            }
            cb(new Error('请输入合法的邮箱'))
        }
        //验证手机号的规则
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|[0-9]|14[57])[0-9]{8}$/
            if(regMobile.test(value)){
                return cb()
            }
            cb(new Error('请输入合法的手机号'))
        }

        return {
            //所有角色列表数据
            rolesList:[],
             //修改用户对话框的显示
            editDialogVisible: false,
            //查询到的用户信息对象
            editForm: {},

            // 添加用户表单的验证对象
            addFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {validator:checkEmail, trigger: 'blur'}
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:checkMobile, trigger: 'blur'}
                ]
            },

            setRightDialogVisible: false,
            rightsList: [],
            // 树形控件的属性绑定对象
            treeProps:{
                label:'authName',
                children: 'children'
            },
            // 默认选中的节点Id值
            defKeys:[],
            //当前操作权限角色的id
            roleId:''
        }
    },
    created() {
     this.getRolesList()
    },
    methods: {
        //获取所有角色列表
        async getRolesList(){
            const {data: res} = await this.$http.get('roles')
            if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')

            this.rolesList = res.data
            console.log(this.rolesList)
        },
        //显示修改用户对话框
         async showEditDialog(id){
            const{data: res} = await this.$http.get('Roles/'+id)
            if(res.meta.status !== 200){
                return this.$message.error('查询用户失败!')
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },
         //监听修改用户对话框的关闭事件
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        //修改用户信息并提交
        editUserInfo(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return
                const {data: res} = await this.$http.put('roles/'+this.editForm.roleId,{roleName:this.editForm.roleName,
                    roleDesc: this.editForm.roleDesc})
                if(res.meta.status !== 200) return this.$message.error('修改用户信息失败')
                this.$message.success("修改用户信息成功")
                this.getRolesList()
                this.editDialogVisible = false
            })
        },
        //删除用户
        removeUserById(id){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const {data:res} = await this.$http.delete('roles/'+id)
                if(res.meta.status !== 200) throw error
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getRolesList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        // 根据id删除对应的权限
        removeRightById(role,rightId){
            //弹框提示用户是否删除
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if(res.meta.status !== 200) {return this.$message.error('删除权限失败!')}

                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                
                role.children = res.data
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },

        async showSetRightDialog(role){
            // 获取所有权限列表
            this.roleId = role.id
            const {data:res} = await this.$http.get('rights/tree')

            if(res.meta.status !==200) return this.$message.error('获取权限列表失败!')

            this.rightsList = res.data

            this.getLeafkeys(role,this.defKeys)
            this.setRightDialogVisible = true
        },
        // 通过递归的形式,获取角色下所有三级权限的id,并保存到数组中
        getLeafkeys(role,arr){
            //如果当前节点不包括children属性,则是第三级节点
            if(!role.children){
                return arr.push(role.id)
            }

            role.children.forEach(item => {
                this.getLeafkeys(item,arr)
            });
        },
        //分配权限对话框关闭时清空默认值
        setRightDialogClosed(){
            this.defKeys = []
        },
        // 点击为用户分配权限
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys(),
            ]

            const idStr = keys.join(',')

            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})

            if(res.meta.status !==200) return this.$message.error('分配权限失败!')

            this.$message.success('分配权限成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom{
        border-top: 1px solid #eee;
    }
    .vcenter{
        display:flex;
        align-items: center;
    }
</style>